<?php include_once '../PlantillasUI/_MainLayout.php'; ?>
<?php include_once '../Model/OrdenDetailDao.php';?>
<?php include_once '../Model/AttachedFileDao.php';?>
<?php include_once '../Model/PrioridadDao.php';?>
<?php include_once '../Model/OrdenDao.php';?>
<?php include_once '../Model/StepLogDao.php';?>
<style type="text/css">
    .botonEnviar{
        color: #2a6496;
    }

</style>

<div id="wrapper">
    <div class="row">

        <div class="col-xs-2 col-sm-2"></div>
        <div class="col-xs-8 col-sm-8">
            <h1>Purchase order</h1>
            <?php
                if(isset($_GET['s']) && strcmp($_GET['s'],'CHD') == 0){
            ?>
            <div class="alert alert-warning alert-dismissible" role="alert">
              <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
              <strong>Notice</strong>, this order is waiting for changes to made, please read the comments for more information.
            </div>
            <?php } ?>
        </div>
        <div class="col-xs-2 col-sm-2"></div>
    </div>
    <div class="row">
        <div class="col-md-2"></div>
        <div class="col-xs-12 col-sm-12 col-md-8">

            <form class="form-inline" role="form" method="post">
                <input type="text" class="form-control" id="idOrden" name="idOrden" value="<?php echo $_GET['idOrden']?>" style="display: none;">
                <input type="text" class="form-control" id="state" name="state" value="<?php echo $_GET['s']?>" style="display: none;">
                <input type="text" class="form-control" id="ordenDetail" name="ordenDetail" placeholder="#" style="display: none;">
                <div class="table-responsive">
                    <table id="table-insert" class="table-insert"  style="display:none;">
                        <tr>
                            <th style="min-width: 90px; max-width: 90px; width: 90px;">Quantity<span class="badge">*</span></th>
                            <th style="min-width: 260px; max-width: 260px; width: 260px;">Description<span class="badge">*</span></th>
                            <th style="min-width: 190px; max-width: 190px; width: 190px;">Provider</th>
                            <th style="min-width: 110px; max-width: 110px; width: 110px;">Discount</th>
                            <th style="min-width: 110px; max-width: 110px; width: 110px;">Unit price</th>
                            <th style="min-width: 127px; max-width: 127px; width: 127px;">Total</th>
                        </tr>
                        <?php
                        if($_GET['idOrden']=='' || $_GET['idOrden']=='0'){

                            for($i = 0; $i<5; $i++) {
                                echo '<tr id='.$i.' class="data">
                                    <td><input type="text" class="form-control required unsigned cantidad" id="cantidad" maxlength="5" max="1000" name="cantidad"></td>
                                    <td style="padding-left: 2px; padding-right: 0px;"><input type="text" class="form-control required" id="descripcion" maxlength="150" name="descripcion"></td>
                                    <td><input type="text" class="form-control" id="proveedor" maxlength="50" name="proveedor"></td>
                                    <td>
                                        <div class="input-group">
                                            <input type="text" class="form-control unsignedFloat discount" max="100" id="discount" name="discount" maxlength="5" placeholder="0">
                                            <div class="input-group-addon">%</div>
                                        </div>
                                    </td>
                                    <td>
                                        <div class="input-group" style="padding-left: 2px; padding-right: 2px;">
                                            <div class="input-group-addon">$</div>
                                            <input type="text" class="form-control unsignedFloat precioUnitario" max="10000" maxlength="5" id="precioUnitario" name="precioUnitario" placeholder="0">
                                        </div>
                                    </td>
                                    <td><div class="form-control total noSave" id="total" name="total"></div></td>
                                </tr>';
                            }
                        }
                        ?>
                    </table>
                    <span class="badge badgeNuevo"> * </span><span class="badgeNuevo">Required fields</span>
                    <div class="alert alert-danger" role="alert" style="display: none;">
                        <span class="alertText"></span>
                        <a href="#" class="close closeAlert">&times;</a>
                    </div>
                    <div class="inline-derecha">

                        <?php
                            if($_GET['idOrden']=='' || $_GET['idOrden']=='0'){
                        ?>

                            <button type="button" class="btn btn-link" id="addRow">
                                <span class="glyphicon glyphicon-plus"></span>
                                <span>Add row</span>
                            </button>
                            <button type="button" class="btn btn-link" id="attached">
                                <span class="glyphicon glyphicon-upload"></span>
                                <span>Add files</span>
                            </button>
                            <button type="button" class="btn btn-link" id="cancel">
                                <span class="glyphicon glyphicon-remove-circle"></span>
                                <span>Cancel</span>
                            </button>
                        <?php
                            } else {
                                if(strcmp($rol,'PRO') != 0) {
                        ?>
                                <button type="button" class="btn btn-link" data-toggle="popover" data-placement="top">Set priority</button>

                        <?php
                            }
                        ?>
                            <button type="button" class="btn btn-link" id="back">
                                <span class="glyphicon glyphicon-arrow-left"></span>
                                <span>Back to history</span>
                            </button>
                            <?php if(strcmp($_GET['s'],'CHD')==0) { ?>
                                <button type="button" class="btn btn-link" id="addDet">
                                    <span class="glyphicon glyphicon-plus"></span>
                                    <span>Add new item</span>
                                </button>
                                <button type="button" class="btn btn-link" id="attached">
                                <span class="glyphicon glyphicon-upload"></span>
                                    <span>Add files</span>
                                </button>
                                <button type="button" class="btn btn-success" id="save">
                                    <span class="glyphicon glyphicon-send"></span>
                                    <span>Send  Changes</span>
                                </button>
                            <?php } ?>
                        <?php
                            }
                            if($_GET['idOrden']!='' && $_GET['idOrden']!='0' && strcmp($rol,'PRO') != 0 && strcmp($_GET['s'],'CHD') != 0 ) {
                        ?>


                            <button id="doChanges" type="button" class="btn btn-warning">
                                <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
                                Do changes
                            </button>
                            <button id="aproveOrden" type="button" class="btn btn-success">
                                <span class="glyphicon glyphicon-thumbs-up" aria-hidden="true"></span>
                                Aprove orden
                            </button>
                            <button id="NotaproveOrden" type="button" class="btn btn-danger">
                                <span class="glyphicon glyphicon-thumbs-down" aria-hidden="true"></span>
                                Not aprove orden
                            </button>

                        <?php
                            }
                        ?>
                        <button type="button" class="btn btn-link" id="limpiar">
                            <span class="glyphicon glyphicon-repeat"></span>
                            <span>Clean all</span>
                        </button>
                        <?php
                            if($_GET['idOrden']=='' || $_GET['idOrden']=='0'){
                        ?>
                        <button type="button" class="btn btn-success" id="save">
                            <span class="glyphicon glyphicon-send"></span>
                            <span>Send orden</span>
                        </button>
                        <?php
                            }
                        ?>
                    </div>
                </div>
            </form>
            <div id="popover_content_wrapper" class="prioridad" style="color:#ffffff; display: none;">
                <?php
                    $prioridades = getAllPriorities();
                    $cant = count($prioridades);
                    $idOrden = $_GET['idOrden'];

                    $ordenActual = getOrdenById($idOrden);

                    if(strcmp($rol,'PRO') != 0 && isset($idOrden) && $idOrden>0) {
                        for ($i = 0; $i < $cant; $i++) {
                            echo '<label class="radio">';
                            echo '<input type="radio" name="prioridad" orden='.$idOrden.' class="radio" id="prioridad'.$i.'" value="'.$prioridades[$i]['idPrioridad'].'"';

                            if(strcmp($ordenActual[0]['idPrioridad'], $prioridades[$i]['idPrioridad'])==0){
                                echo 'checked';
                            }
                            echo '>';
                            echo '<span class="glyphicon '.$prioridades[$i]['icono'].'" aria-hidden="true"></span>'.$prioridades[$i]['idPrioridad'];
                            echo '</label>';
                            echo '<br/>';
                        }
                    }
                ?>

            </div>
            <div class="table-responsive" style="height: 300px;  overflow: auto; display:none;">
                <table id="hotPreview" class="table table-hover">
                    <tr class="data">
                        <th>Preview</th>
                        <th>nombre</th>
                        <th>Mb</th>
                        <th></th>
                    </tr>
                </table>
            </div>
            <div class="jumbotron" id='filezone' style="height: 300px;  overflow: auto; display: none;">
                <form action="../Controller/fileController.php?idOrden=<?php echo $idOrden; ?>" method="post" id="dropzone" class="dropzone" enctype="multipart/form-data" style="margin-top: -45px;">
                    <div class="fallback">
                        <input name="userfile" type="file" multiple/>
                    </div>
                </form>
            </div>
            <div class="table-responsive">
                <table class="table tableResults table-hover" style="display:none;">
                    <tr>
                        <th>Quantity</th>
                        <th>Description</th>
                        <th>Provider</th>
                        <th>Discount</th>
                        <th>Unit price</th>
                        <th>Total</th>
                        <?php
                            $results = getDetailById($idOrden);
                            if(isset($_GET['s']) && strcmp($_GET['s'],'CHD') == 0 && strcmp($results[0]['creationUser'],$user)== 0){
                                echo '<th>Actions</th>';
                            }
                        ?>
                    </tr>

                    <?php

                        $results = getDetailById($idOrden);
                        $cant = count($results);
                        for ($i = 0; $i < $cant; $i++) {
                            echo '<tr class="data" id="' . $results[$i]['ordenDetail'] . '">';
                            echo '<td>' . $results[$i]['cantidad'] . '</td>';
                            echo '<td>' . $results[$i]['descripcion'] . '</td>';
                            echo '<td>' . $results[$i]['proveedor'] . '</td>';
                            echo '<td>' . $results[$i]['discount'] . '%</td>';
                            echo '<td>$' . $results[$i]['precioUnitario'] . '</td>';
                            echo '<td>$' . $results[$i]['total'] . '</td>';
                            if(strcmp($_GET['s'],'CHD') == 0 && strcmp($results[$i]['creationUser'],$user)== 0){
                                echo '<td>';
                                echo '<button type="button" class="btn btn-default btn-xs editar"data-toggle="tooltip" data-placement="top" title="Edit">'
                                        . '<span class="glyphicon glyphicon-edit"></span></button>';
                                echo '<button type="button" class="btn btn-default btn-xs remover" data-toggle="tooltip" data-placement="top" title="Remove">'
                                        . '<span class="glyphicon glyphicon-trash"></span></button>'
                                        . '</td>';
                            }
                            echo '</tr>';
                        }
                    ?>
                </table>
                <?php
                    $adjuntos = getFilesByOrden($idOrden);
                    $cant = count($adjuntos);
                    if($cant>0){
                        echo '<h4 style="color:#ffffff">Attached files</h4>';
                        echo '<table class="table table-hover tableResults" style="display:none;">';

                        for ($i = 0; $i < $cant; $i++) {
                            echo '<tr class="data filesPreview" id="' . $adjuntos[$i]['idAttached'] . '" type="'. $adjuntos[$i]['type'] .'">';
                            if(strpos($adjuntos[$i]['type'],'image')!== false){
                                $mime = $adjuntos[$i]['type'];
                                $b64Src = "data:".$mime.";base64," . base64_encode($adjuntos[$i]["content"]);
                                echo '<td><img style="max-height: 35px;" src="'.$b64Src.'" alt="' . $adjuntos[$i]['name'] . '" /></td>';
                            } else {
                                if(strpos($adjuntos[$i]['type'],'pdf')!== false){
                                    echo '<td><img style="max-height: 35px;" src="../Resources/img/thumbnail_pdf.png" /></td>';
                                } else {
                                    echo '<td><img style="max-height: 35px;" src="../Resources/img/thumbnail_word.png" /></td>';
                                }
                            }
                            echo '<td>' . $adjuntos[$i]['name'] . '</td>';
                            echo '<td>' . $adjuntos[$i]['Mb'] . ' Mb</td>';
                            echo '</tr>';
                        }
                        echo '</table>';
                    }
                ?>
            </div>
        </div>
        <div class="col-md-2"></div>
    </div>
</div>
<div class="cargando">
    <div id="mensaje">
        Please wait... <img src="../Resources/img/ajax-loader.gif"/>
    </div>
</div>
<div class="previewDialog fixed-dialog">
    <div id="mensaje"></div>
</div>

<script type="text/javascript">

    $('.cargando' ).dialog({ dialogClass: "no-close", autoOpen: false, modal: true,width: "30%", sticky: true});
    $('.previewDialog' ).dialog({ dialogClass: "no-close", autoOpen: false, modal: true, width: "90%",height: 600});
    if($('#idOrden').val()==='0'){
        $('.tableResults').hide();
        $('.table-insert').show();
        $('.badgeNuevo').show();
        $('#limpiar').show();
        $('#save').show();
    } else {
        $('.tableResults').show();
        $('.table-insert').hide();
        $('.badgeNuevo').hide();
        $('#limpiar').hide();
        if($('#state').val()!=='CHD')
            $('#save').hide();
    }
    if($('#state').val()!=='CHD')
        $('#save').attr("disabled","disabled");
    $('#limpiar').click(function (){
        $('#save').attr("disabled","disabled");
        $('.form-control').each(function() {
            $(this).val('');
            $('.has-error').removeClass('has-error');
            $('.alert').hide('slow');
            if($(this).is('div')){
                $(this).html('');
            }
        });
    });
    function hayData(){
        var tBody = $('.table-insert').children();
        var encabezados = ["Quantity","Description","Provider","Discount","UnitPrice"];
        var json = getJson_tablaInsertar(tBody,encabezados,false);
        if(json==='{"data":[]}') {
            $('#save').attr("disabled","disabled");
        }else{
            $('#save').removeAttr("disabled");
        }
    }
    $('#save').click(function (){
        var mensaje = 'You are going to save and send this order, make sure you have entered all you need for this order. Want to continue?';
        if($("#state").val()==='CHD'){
            var mensaje = 'You will send back with changes this orden, do you want continue?'
            $('.cargando').children('#mensaje').html(mensaje + '<br/>Comment: <br/><input type="text" name="commentDialog" id="commentDialog" style="height: 45px;width: 100%;"/>');
            $('.cargando').dialog({buttons:{
                    "Ok": {  text: 'Send', class: 'btn btn-link botonEnviar', click: function () {
                            $('.cargando').dialog( 'close' );
                            ajaxPost("../Controller/StepLogController.php","data="+$('#idOrden').val()+',PAC,'+$('#commentDialog').val(), "text", "#");
                            ajaxPost("../Controller/changeStepController.php?comment="+$('#commentDialog').val(),"data="+$('#idOrden').val()+',PAC', "text", "OrdenCompra.php");
                    }},
                    "No": { text: 'Do not send.', class: 'btn btn-primary', click: function() {
                            $('.cargando').dialog( 'close' );
                    }}}});
            $('.cargando').dialog( "open" );
        } else {
            $('.cargando').children('#mensaje').html(mensaje + '<br/>Comment: <br/><input type="text" name="commentDialog" id="commentDialog" style="height: 45px;width: 100%;"/>');
            $('.cargando').dialog({buttons:{
                                "Ok": {  text: 'Send', class: 'btn btn-link botonEnviar', click: function () {
                                    $('.cargando').dialog( 'close' );
                                    $('.cargando').children('#mensaje').html('Please wait... <img src="../Resources/img/ajax-loader.gif"/>');
                                    $('.cargando').dialog("option", "buttons", {});
                                    var tBody = $('.table-insert').children();
                                    var encabezados = ["Quantity","Description","Provider","Discount","UnitPrice"];
                                    var json = getJson_tablaInsertar(tBody,encabezados,true);
                                    $('.cargando').dialog( "open" );
                                    if(json==='{"data":[]}') {
                                        $('.cargando').children('#mensaje').html('Empty list of items. please fill the required fields before add to the order.');
                                        $('.cargando').dialog({buttons: { "Ok": {  text: 'Ok', class: 'btn btn-primary', click: function () {
                                            $('.cargando').dialog( 'close' );
                                        }}}});
                                    } else {
                                        var page = 'OrdenCompraDet.php';
                                        if($('#idOrden').val()>0) { page = page + '?idOrden='+$('#idOrden').val(); }
                                        else { page = 'OrdenCompra.php'; }

                                        ajaxPost("../Controller/newOrdenDetailsController.php?"
                                                +"act=insert"
                                                +"&idOrden="+$('#idOrden').val()
                                                +"&ordenDetail="+$('#ordenDetail').val()
                                                ,"data="+json, "text", page);
                                    }
                                }},
                                "No": { text: 'No, do not continue.', class: 'btn btn-primary', click: function() {
                                    $('.cargando').dialog( 'close' );
                                }}}});
            $('.cargando').dialog( "open" );
        }
    });
    $('.editar').click(function(){
        var idDet = $(this).parent().parent().attr('id');
        var _tr = $(this).parent().parent();

        $('.cargando').children('#mensaje').html(
            '<form class="form-horizontal">'
            + '<input type="text" class="form-control" id="idDet_dialog" value = "'+idDet+'" style="display: none;">'
            + '<div class="form-group">'
                + '<label for="cantidad_dialog" class="col-sm-3 control-label">Quantity: </label>'
                + '<div class="col-sm-9">'
                    + '<input type="text" class="form-control" id="cantidad_dialog" placeholder="0" value="'+$(_tr).children().eq(0).text()+'">'
                + '</div>'
            + '</div>'
            + '<div class="form-group">'
                + '<label for="descripcion_dialog" class="col-sm-3 control-label">Description: </label>'
                + '<div class="col-sm-9">'
                    + '<input type="text" class="form-control" id="descripcion_dialog" placeholder="Description" value="'+$(_tr).children().eq(1).text()+'">'
                + '</div>'
            + '</div>'
            + '<div class="form-group">'
                + '<label for="proveedor_dialog" class="col-sm-3 control-label">Provider: </label>'
                + '<div class="col-sm-9">'
                    + '<input type="text" class="form-control" id="proveedor_dialog" placeholder="Provider" value="'+$(_tr).children().eq(2).text()+'">'
                + '</div>'
            + '</div>'
            + '<div class="form-group">'
                + '<label for="descuento_dialog" class="col-sm-3 control-label">Discount: </label>'
                + '<div class="col-sm-6 input-group">'
                    + '<input type="text" class="form-control" id="descuento_dialog" placeholder="0" value="'+$(_tr).children().eq(3).text().replace("%","")+'">'
                    + '<div class="input-group-addon">%</div>'
                + '</div>'
            + '</div>'
            + '<div class="form-group">'
                + '<label for="precioUnitario_dialog" class="col-sm-3 control-label">Unit price: </label>'
                + '<div class="col-sm-6 input-group">'
                    + '<div class="input-group-addon">$</div>'
                    + '<input type="text" class="form-control" id="precioUnitario_dialog" placeholder="0" value="'+$(_tr).children().eq(4).text().replace("$","")+'">'
                + '</div>'
            + '</div>'
            + '</form>'
            );
        $('.cargando').dialog({buttons:{
            "Ok": {  text: 'Save', class: 'btn btn-link botonEnviar', click: function () {
                var error = 0;
                if($('#cantidad_dialog').val()===''){
                    error++;
                    $('#cantidad_dialog').parent().parent().addClass('has-error');
                }
                if($('#descripcion_dialog').val()===''){
                    error++;
                    $('#descripcion_dialog').parent().parent().addClass('has-error');
                }
                if($('#precioUnitario_dialog').val()===''){
                    error++;
                    $('#precioUnitario_dialog').parent().parent().addClass('has-error');
                }
                if(error===0){
                    json = '{"data":['
                        +'"' + $('#idDet_dialog').val() +'",'
                        +'"' + $('#cantidad_dialog').val() +'",'
                        +'"' + $('#descripcion_dialog').val() +'",'
                        +'"' + $('#proveedor_dialog').val() +'",'
                        +'"' + $('#descuento_dialog').val() +'",'
                        +'"' + $('#precioUnitario_dialog').val() +'"'
                        + ']}';

                    ajaxPost("../Controller/newOrdenDetailsController.php?"
                            +"act=update&idOrden="+$('#idOrden').val()
                            ,"data="+json, "text", 'OrdenCompraDet.php?idOrden='+$('#idOrden').val()+'&s=CHD');
                    $('.btn-success').removeAttr("disabled");
                }
            }},
            "No": { text: 'Cancel', class: 'btn btn-primary', click: function() { $('.cargando').dialog( 'close' ); }}}});
        $('.cargando').dialog( "open" );

    });
    $('#addDet').click(function(){
        $('.cargando').children('#mensaje').html(
            '<form class="form-horizontal">'
            + '<input type="text" class="form-control" id="idDet_dialog" value = "" style="display: none;">'
            + '<div class="form-group">'
                + '<label for="cantidad_dialog" class="col-sm-3 control-label">Quantity: </label>'
                + '<div class="col-sm-9">'
                    + '<input type="text" class="form-control unsigned" max="10000" id="cantidad_dialog" placeholder="0" value="">'
                + '</div>'
            + '</div>'
            + '<div class="form-group">'
                + '<label for="descripcion_dialog" class="col-sm-3 control-label">Description: </label>'
                + '<div class="col-sm-9">'
                    + '<input type="text" class="form-control" id="descripcion_dialog" placeholder="Description" value="">'
                + '</div>'
            + '</div>'
            + '<div class="form-group">'
                + '<label for="proveedor_dialog" class="col-sm-3 control-label">Provider: </label>'
                + '<div class="col-sm-9">'
                    + '<input type="text" class="form-control" id="proveedor_dialog" placeholder="Provider" value="">'
                + '</div>'
            + '</div>'
            + '<div class="form-group">'
                + '<label for="descuento_dialog" class="col-sm-3 control-label">Discount: </label>'
                + '<div class="col-sm-6 input-group">'
                    + '<input type="text" class="form-control unsignedFloat" max="100" id="descuento_dialog" placeholder="0" value="">'
                    + '<div class="input-group-addon">%</div>'
                + '</div>'
            + '</div>'
            + '<div class="form-group">'
                + '<label for="precioUnitario_dialog" class="col-sm-3 control-label">Unit price: </label>'
                + '<div class="col-sm-6 input-group">'
                    + '<div class="input-group-addon">$</div>'
                    + '<input type="text" class="form-control unsignedFloat" max="10000" id="precioUnitario_dialog" placeholder="0" value="">'
                + '</div>'
            + '</div>'
            + '</form>'
            );
        $('.cargando').dialog({buttons:{
            "Ok": {  text: 'Save', class: 'btn btn-link botonEnviar', click: function () {
                var error = 0;
                if($('#cantidad_dialog').val()===''){
                    error++;
                    $('#cantidad_dialog').parent().parent().addClass('has-error');
                }
                if($('#descripcion_dialog').val()===''){
                    error++;
                    $('#descripcion_dialog').parent().parent().addClass('has-error');
                }
                if($('#precioUnitario_dialog').val()===''){
                    error++;
                    $('#precioUnitario_dialog').parent().parent().addClass('has-error');
                }
                if(error===0){
                    json = '{"data":['
                        +'"' + $('#idDet_dialog').val() +'",'
                        +'"' + $('#cantidad_dialog').val() +'",'
                        +'"' + $('#descripcion_dialog').val() +'",'
                        +'"' + $('#proveedor_dialog').val() +'",'
                        +'"' + $('#descuento_dialog').val() +'",'
                        +'"' + $('#precioUnitario_dialog').val() +'"'
                        + ']}';

                    ajaxPost("../Controller/newOrdenDetailsController.php?"
                            +"act=update&idOrden="+$('#idOrden').val()
                            ,"data="+json, "text", 'OrdenCompraDet.php?idOrden='+$('#idOrden').val()+'&s=CHD');
                }
            }},
            "No": { text: 'Cancel', class: 'btn btn-primary', click: function() { $('.cargando').dialog( 'close' ); }}}});
        $('.cargando').dialog( "open" );

    });
    $('body').delegate('#descripcion_dialog','keyup',function (event) {
        $('#descripcion_dialog').parent().parent().removeClass('has-error');
    });
    $('.remover').click(function(){
        var mensaje = 'You are going to remove this item from the orden. Want to continue?';
        $('.cargando').children('#mensaje').html(mensaje);
        $('.cargando').dialog({buttons:{
            "Ok": {  text: 'Send', class: 'btn btn-link botonEnviar', click: function () {
                ordenDet = $(this).parent().parent().attr('id');
                var page = 'OrdenCompraDet.php';
                if($('#idOrden').val()>0) { page = page + '?idOrden='+$('#idOrden').val(); }
                else { page = 'OrdenCompra.php'; }
                ajaxPost("../Controller/newOrdenDetailsController.php?"
                        +"act=delete"
                        ,"data="+ordenDet, "text", page);
            }},
            "No": { text: 'No, do not continue.', class: 'btn btn-primary', click: function() { $('.cargando').dialog( 'close' ); }}}});
        $('.cargando').dialog( "open" );

    });
    function manipularData(data,page){
        var mensaje = '';
        if(data==='-1' || data===-1){
            mensaje = 'Empty list of items.';
        } else {
            if(data==='-2' || data===-2) {
                mensaje = 'Cannot create a new orden.';
            } else {
                mensaje = data + ' items saved.';
            }
        }
        if(data==='delete') {
            if(page!=='#'){
                location.href = page;
            }
        } else {
            if(data==='aproved') {
                mensaje = "Orden aproved."
                $('.cargando').dialog( "open" );
            }
            if(data==='changed') {
                mensaje = "Orden changed."
                $('.cargando').dialog( "open" );
            }
            $('.cargando').children('#mensaje').html(mensaje);
            $('.cargando').dialog({buttons: { "Ok": {  text: 'Ok', class: 'btn btn-primary', click: function () {
                                    $('.cargando').dialog( 'close' );
                                    if(data!=='-1'){
                                        if(page!=='#'){
                                            location.href = page;
                                        }
                                    }
                                }}}});
        }
    }
    $('body').delegate('.discount','keyup',function (event) {
        var valD = $(this).val();
        var valP = $(this).parent().parent().next().children().children('#precioUnitario').val();
        var valC = $(this).parent().parent().parent().children().first().children('#cantidad').val();
        if(!isNaN(valD) && valD.length>0){
            if(!isNaN(valP) && valP.length>0){
                if(!isNaN(valP) && valP.length>0){
                    var max = $(this).attr('max');
                    if(max!==undefined){
                         valD = parseFloat(valD);
                         valD = parseFloat(valD);
                         max = parseFloat(max);
                         if(valD<=max){
                           var total = (valP*valC) - (valP*valC*(valD/100));
                            total = total.toFixed(2);
                            $(this).parent().parent().parent().children().last().children('#total').html(total);
                         }
                    }
                }
            } else { $(this).parent().parent().parent().children().last().children('#total').html(0); }
        } else { // asumo descuento = 0
            $(this).parent().parent().parent().children().last().children('#total').html(valP*valC);
        }
    });
    $('body').delegate('.cantidad','keyup',function (event) {
        var valC = $(this).val();
        var valD = $(this).parent().parent().children().eq(3).children().children('#discount').val();
        var valP = $(this).parent().parent().children().eq(4).children().children('#precioUnitario').val();

        if(!isNaN(valD) && valD.length>0){
            if(!isNaN(valP) && valP.length>0){
                if(!isNaN(valP) && valP.length>0){
                    var max = $(this).attr('max');
                    if(max!==undefined){
                         valD = parseFloat(valD);
                         valD = parseFloat(valD);
                         max = parseFloat(max);
                         if(valD<=max){
                            var total = (valP*valC) - (valP*valC*(valD/100));
                            total = total.toFixed(2);
                            $(this).parent().parent().children().eq(5).children('#total').html(total);
                         }
                    }
                }
            } else { $(this).parent().parent().children().eq(5).children('#total').html(0); }
        } else { // asumo descuento = 0
            $(this).parent().parent().children().eq(5).children('#total').html(valP*valC);
        }
    });
    $('body').delegate('.precioUnitario','keyup',function (event) {
        var valP = $(this).val();
        var valD = $(this).parent().parent().parent().children().eq(3).children().children('#discount').val();
        var valC = $(this).parent().parent().parent().children().eq(0).children('#cantidad').val();

        if(!isNaN(valD) && valD.length>0){
            if(!isNaN(valP) && valP.length>0){
                if(!isNaN(valP) && valP.length>0){
                    var max = $(this).attr('max');
                    if(max!==undefined){
                         valD = parseFloat(valD);
                         valD = parseFloat(valD);
                         max = parseFloat(max);
                         if(valD<=max){
                            var total = (valP*valC) - (valP*valC*(valD/100));
                            total = total.toFixed(2);
                            $(this).parent().parent().next().children('#total').html(total);
                         }
                    }
                }
            } else { $(this).parent().parent().next().children('#total').html(0); }
        } else { // asumo descuento = 0
            $(this).parent().parent().next().children('#total').html(valP*valC);
        }
    });
    $('body').delegate('.hotDelete','click',function(event) {
        var name = $(this).parent().parent().attr('fileName');
        var json='{"data":["' + name + '"]}';
        ajaxPost("../Controller/fileController.php?idOrden="+$('#idOrden').val(),"data="+json, "text", "#");
        $(this).parent().parent().remove();
        if($('#hotPreview').children().children().length==1){
            var options = {};
            $('#hotPreview').parent().hide('blind',options,800);
            $('#attached').html('<span class="glyphicon glyphicon-paperclip"></span><span>Add files</span>');
        }
    });
    $('#addRow').click(function() {
        $('.table-insert').show();
        $('.badgeNuevo').show();
        $('#limpiar').show();
        $('#save').show();
        $('.table-insert > tbody:last').append(
                '<tr class="data">'
                + ' <td><input type="text" class="form-control required unsigned cantidad" min="1" id="cantidad" maxlength="11" name="cantidad"></td>'
                + ' <td><input type="text" class="form-control required" id="descripcion" maxlength="150" name="descripcion"></td>'
                + ' <td><input type="text" class="form-control" id="proveedor" maxlength="50" name="proveedor"></td>'
                + ' <td>'
                + '    <div class="input-group">'
                + '        <input type="text" class="form-control unsignedFloat discount" min="0" id="discount" name="discount" maxlength="5" placeholder="0">'
                + '        <div class="input-group-addon">%</div>'
                + '    </div>'
                + ' </td>'
                + ' <td>'
                + '    <div class="input-group">'
                + '        <div class="input-group-addon">$</div>'
                + '        <input type="text" class="form-control required unsignedFloat precioUnitario" min="0" maxlength="5" id="precioUnitario" name="precioUnitario" placeholder="0">'
                + '    </div>'
                + ' </td>'
                + ' <td><div class="form-control total noSave" id="total" name="total"></div></td>'
                + ' </tr>'
            );

    });
    $('body').delegate('input','keyup',function (event) {
        hayData();
    });
    $('#aproveOrden').click(function () {
        var mensaje = 'You will aprove this orden, do you want continue?'
        $('.cargando').children('#mensaje').html(mensaje + '<br/>Comment: <br/><input type="text" name="commentDialog" id="commentDialog" style="height: 45px;width: 100%;"/>');
        $('.cargando').dialog({buttons:{
                "Ok": {  text: 'Aprove', class: 'btn btn-link botonEnviar', click: function () {
                        $('.cargando').dialog( 'close' );
                        ajaxPost("../Controller/StepLogController.php","data="+$('#idOrden').val()+',APR,'+$('#commentDialog').val(), "text", "#");
                        ajaxPost("../Controller/aprovedController.php","data="+$('#idOrden').val(), "text", "OrdenCompra.php");
                }},
                "No": { text: 'Do not aprove.', class: 'btn btn-primary', click: function() {
                        $('.cargando').dialog( 'close' );
                }}}});
        $('.cargando').dialog( "open" );
    });
    $('#doChanges').click(function () {
        var mensaje = 'You will send back for changes, do you want continue?'
        $('.cargando').children('#mensaje').html(mensaje + '<br/>Comment: <br/><input type="text" name="commentDialog" id="commentDialog" style="height: 45px;width: 100%;"/>');
        $('.cargando').dialog({buttons:{
                "Ok": {  text: 'Send', class: 'btn btn-link botonEnviar', click: function () {
                        $('.cargando').dialog( 'close' );
                        ajaxPost("../Controller/StepLogController.php","data="+$('#idOrden').val()+',CHD,'+$('#commentDialog').val(), "text", "#");
                        ajaxPost("../Controller/changeStepController.php","data="+$('#idOrden').val()+',CHD', "text", "OrdenCompra.php");
                }},
                "No": { text: 'Do not send.', class: 'btn btn-primary', click: function() {
                        $('.cargando').dialog( 'close' );
                }}}});
        $('.cargando').dialog( "open" );
    });
    $('#NotaproveOrden').click(function () {
        var mensaje = 'You reject this order, would you continue?'
        $('.cargando').children('#mensaje').html(mensaje + '<br/>Comment: <br/><input type="text" name="commentDialog" id="commentDialog" style="height: 45px;width: 100%;"/>');
        $('.cargando').dialog({buttons:{
                "Ok": {  text: 'Reject', class: 'btn btn-link botonEnviar', click: function () {
                        $('.cargando').dialog( 'close' );
                        ajaxPost("../Controller/StepLogController.php","data="+$('#idOrden').val()+',DND,'+$('#commentDialog').val(), "text", "#");
                        ajaxPost("../Controller/changeStepController.php","data="+$('#idOrden').val()+',DND', "text", "OrdenCompra.php");
                }},
                "No": { text: 'Do not reject.', class: 'btn btn-primary', click: function() {
                        $('.cargando').dialog( 'close' );
                }}}});
        $('.cargando').dialog( "open" );
    });
    $('#cancel').click(function() {
        var tBody = $('.table-insert').children();
        var encabezados = ["Quantity","Description","Provider","Discount","UnitPrice"];
        var json = getJson_tablaInsertar(tBody,encabezados,false);
        if(json!=='{"data":[]}'){
            var mensaje = 'All changes will lose, do you want continue?'
            $('.cargando').children('#mensaje').html(mensaje);
            $('.cargando').dialog({buttons:{
                                "Ok": {  text: 'Ok', class: 'btn btn-link botonEnviar', click: function () {
                                    $('.cargando').dialog( 'close' );
                                    location.href = 'OrdenCompra.php';
                                }},
                                "No": { text: 'No, continue here.', class: 'btn btn-primary', click: function() {
                                    $('.cargando').dialog( 'close' );
                                }}}});
            $('.cargando').dialog( "open" );
        } else {
            location.href = 'OrdenCompra.php';
        }

    });
    $('#back').click(function() {
        location.href = 'OrdenCompra.php';
    });
    $('#attached').click(function() {
        var options = {};
        $('#hotPreview').parent().show('blind',options,800);
        $('#dropzone').click();
        $(this).html('<span class="glyphicon glyphicon-paperclip"></span><span>Add more files</span>');
    });
    $('.filesPreview').click(function() {
        $('.previewDialog').children('#mensaje').html('Please wait... <img src="../Resources/img/ajax-loader.gif"/>');
       if($(this).attr('type').indexOf('image')>-1){ // si es imagen solo cargo por ajax
            $('.previewDialog').children('#mensaje').load('../Files/previewFiles.php?id='+$(this).attr('id'));
            $('.previewDialog').dialog({buttons: { "Close": {  text: 'Close', class: 'btn btn-primary', click: function () {
                $('.previewDialog').dialog( 'close' );
                $("body").css("overflow", "auto");
                $('.previewDialog').children('#mensaje').html('Please wait... <img src="../Resources/img/ajax-loader.gif"/>');
            }}}});
            $('.previewDialog').dialog( "open" );
            $("body").css("overflow", "hidden");
       } else {
           if($(this).attr('type').indexOf('pdf')>-1) { // pdf no se carga por ajax así que uso iframe :(
                $('.previewDialog').children('#mensaje').html('<iframe width="100%" height="450" src="../Files/previewFiles.php?id='+$(this).attr('id') + '"></iframe>');
                $('.previewDialog').dialog({buttons: { "Close": {  text: 'Close', class: 'btn btn-primary', click: function () {
                    $('.previewDialog').dialog( 'close' );
                    $("body").css("overflow", "auto");
                    $('.previewDialog').children('#mensaje').html('Please wait... <img src="../Resources/img/ajax-loader.gif"/>');
                }}}});
                $('.previewDialog').dialog( "open" );
                $("body").css("overflow", "hidden");
           } else {
               // cualquier otro tipo de archivo, lo descargo
               location.href = '../Files/downloadFiles.php?id='+$(this).attr('id');
           }
       }
    });
    Dropzone.options.dropzone = {
        maxFilesize: 16,
        acceptedFiles: "image/*,application/pdf,.docx,.doc",
        addRemoveLinks: true
    }
    $('body').delegate('.radio','click',function (){
        var json = '{"data":["' + $(this).val() + '", "'+ $(this).attr('orden') +'"]}';
        ajaxPost("../Controller/PriorityController.php","data="+json, "text", "#");
    });
</script>
<?php include_once '../PlantillasUI/_footerLayout.php'; ?>
